﻿app.factory('ContactsService', function ($http, $q) {
   
    // Data container...
    var myContacts = [];

    // fire base url
    var myFb = 'https://315demo.firebaseio.com/contacts415/.json'

    //READ...
    function getContacts() {
        var def = $q.defer();   // defines the Promise
        $http({
            url: myFb,
            method: 'GET'
        }).success(function (data) {
           // populate the array...
            myContacts = []; // reset the array to empty
            for (var i in data) {
                data[i].guid = i; // set the prop of guid to the FB guid
                myContacts.push(data[i]) // 
            }

            console.log("data came back & parsed:", myContacts)
            // resolve with data that came back
            def.resolve(myContacts); // is setting up the binding...
        }).error(function () {
            // reject the promise if error
            def.reject();
            console.log("there was a problem");
        });
        return def.promise;     // return the Promise immediately
        /*
        $http()
        .success()
        .error()
        */
    }

    // CREATE.... 
    function createContact(objToSend) {
        var def = $q.defer(); // set up the promise
        $http({
            url: myFb,
            method: 'POST',
            data: objToSend
        })
        .success(function (dat) {
            console.log('Data returned:', dat)
            myContacts.push(objToSend); // try to add the Object 
            def.resolve(dat); // resolve the promise with data
        })
        .error(function () {
            def.reject(); // resolve the promise with a reject
        })
        return def.promise;
    }

    // UPDATE...
    function updateContact(objToSend, arrIndex) {
        var def = $q.defer(); // set up the promise
        $http({
            url: 'https://315demo.firebaseio.com/contacts415/' + myContacts[arrIndex].guid + '/.json',
            method: 'PUT',
            data: objToSend
        })
        .success(function (dat) {
            console.log('Data returned:', dat);
            myContacts[arrIndex] = objToSend; // save the changes back to the Arr
            def.resolve(dat); // resolve the promise with data
        })
        .error(function () {
            def.reject(); // resolve the promise with a reject
        })
        return def.promise;
    }




    // Expose the Methods & Variables
    return {
        getContacts: getContacts,
        createContact: createContact,
        updateContact: updateContact,
        myContacts: myContacts
    }

});